//
//  PersonDataViewController.m
//  Volver
//
//  Created by admin on 14-10-8.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "PersonDataViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "VOLAppDelegate.h"
#import "User.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

#import "VOLHeadImageView.h"
#import "VOLYanZhengView.h"
#import "VOLRegisterNameView.h"
#import "VOLChangePersonDataViewController.h"


@interface PersonDataViewController ()
{

    VOLAppDelegate *del;
    int currentHeight;
    NSFileManager *manager;
    VOLHeadImageView *loadHeadView;
    JSONDecoder *jd;
    VOLYanZhengView *yanZhengView;
    NSData *imageData;
    
    MBProgressHUD *HUD;
}
@end

@implementation PersonDataViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	//添加返回按钮
    addBackButton();
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc]init];
    //imageData初始化
    imageData = [[NSData alloc] init];
    
}


-(void)viewWillAppear:(BOOL)animated{

    
    //判断跳转来源，判断位置应该在这里，而不是进入loadPerson方法以后
    if (self.sourceFrom == 0) {
        //只有从菜单界面进入个人信息界面时才显示编辑按钮，其它地方跳转过来不能显示编辑
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editPerson)];
        [self.navigationItem.rightBarButtonItem setTintColor:kThemeColor];
        //将currentUser传过去进行初始化界面
        [self loadPerson:del.currentUser];
    }else{
        //如果是从其它地方跳转过来，要将userID传过来，先去加载用户信息，再调用loadPerson方法加载界面
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        [HUD showAnimated:YES whileExecutingBlock:^{
            [self getPartUserInfo:self.userID];
        }];
    }
}

-(void)loadPerson:(User *)user
{

#pragma mark - 用户头像
    float width = self.view.bounds.size.width;
    //    float height = self.view.bounds.size.height;
    self.title = @"个人资料";
    //用来控制各个控件高度位置的全局变量
    currentHeight = 0;
    NSArray *headImage = [[NSBundle mainBundle] loadNibNamed:@"VOLHeadImageView" owner:self options:nil];
    loadHeadView = headImage[0];
    loadHeadView.center = CGPointMake(width/2, (loadHeadView.bounds.size.height/2)+64);
    //
    loadHeadView.headImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    loadHeadView.headImageView.contentMode = UIViewContentModeScaleAspectFill;
    //判断userHead属性是否为空，如果不是则加载头像
    if ((NSNull *)user.userHead != [NSNull null]) {
        
        NSLog(@"加载用户的头像");
        //初始化manager
        manager = [NSFileManager defaultManager];
        //加载图片
        //先判断是否有这个路径存在，如果没有要先创建
        NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/userHead/%d",kGetDocumentsPath,del.currentUser.userID,user.userID];
        if (![manager fileExistsAtPath:imageDocumentPath]) {
            [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        //先从本地查找是否已有图片
        NSString *imagePath = [NSString stringWithFormat:@"%@%d/userHead/%d/%@",kGetDocumentsPath,del.currentUser.userID,user.userID,user.userHead];
        if ([manager fileExistsAtPath:imagePath]) {
            loadHeadView.headImageView.image = [UIImage imageWithContentsOfFile:imagePath];
        }
        else{
            //若不存在，调用方法下载图片
            [del loadHeadImage:user.userHead userID:user.userID headImageView:loadHeadView.headImageView imagePath:imagePath];
        }
    }
    else{
        loadHeadView.headImageView.image = [UIImage imageNamed:@"defaultHead.png"];
    }
    [self.view addSubview:loadHeadView];
    if (self.sourceFrom == 0) {
        //添加单机手势
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addheadimage:)];
        //将触摸事件添加到当前view
        [self.view addSubview:loadHeadView];
        [loadHeadView addGestureRecognizer:tapGestureRecognizer];
        
    }
    currentHeight = loadHeadView.frame.size.height;
    
#pragma mark - 名字、注册时间
    
    NSArray *registername = [[NSBundle mainBundle] loadNibNamed:@"VOLRegisterNameView" owner:self options:nil];
    VOLRegisterNameView *registerNameTime = registername[0];
    registerNameTime.center = CGPointMake(width/2, (currentHeight + registerNameTime.bounds.size.height/2) + 64);
    //为nameLable、registerTimeLable赋值
    registerNameTime.nameLable.text = user.userName;
    NSDate *registerDate = kTransformToDate(user.userRegisterTime);
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    registerNameTime.registerTimeLable.text = [formatter stringFromDate:registerDate];
    [self.view addSubview:registerNameTime];
    currentHeight += registerNameTime.frame.size.height;
    
#pragma mark - 验证
    
    NSArray *yanZheng = [[NSBundle mainBundle] loadNibNamed:@"VOLYanZhengView" owner:self options:nil];
    yanZhengView = yanZheng[0];
    yanZhengView.center = CGPointMake(width/2, (currentHeight + yanZhengView.bounds.size.height/2) + 64);
    //为emailLable、phonenumLable赋值
    if (user.userMail) {
        yanZhengView.emailLable.text = [NSString stringWithFormat:@"%@",user.userMail];
        
    }
    else{
        yanZhengView.emailLable.text = @"";
    }
    
    yanZhengView.phonenumLable.text = user.userPhone;
    [self.view addSubview:yanZhengView];
}
-(void)loademaill{
    if ((NSNull *)del.currentUser.userMail == [NSNull null]) {
        yanZhengView.emailLable.text = @"";
    }else
        
    yanZhengView.emailLable.text = del.currentUser.userMail ;
    
}
#pragma mark - 按钮点击事件
#pragma mark 返回按钮事件
-(void)goBack:(id)sender{
    back;
}

#pragma mark 跳转到编辑个人资料界面
-(void)editPerson
{
    VOLChangePersonDataViewController *changePersonData = [self.storyboard instantiateViewControllerWithIdentifier:@"VOLChangePersonDataViewController"];
    [self.navigationController pushViewController:changePersonData animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 编辑头像手势

-(void)addheadimage:(id)sender{
    
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择照片", nil];
    //    [sheet showInView:self];
    [sheet showInView:self.view];
    
    
}
#pragma mark - 加载用户信息

-(void)getPartUserInfo:(int)userID{
    NSString *urlstr = [NSString stringWithFormat:@"%@user/getPartUserInfo?userID=%d",kHTTPHome,userID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
    
}

#pragma mark - 异步请求代理方法
#pragma mark 请求完成的方法：
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSData *data = [request responseData];
    if (data == nil) {
        return;
    }
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    if (status) {//加载成功，提取信息，加载界面
        NSArray *array = [dic objectForKey:@"partUserInfo"];
        NSDictionary *userInfo = array[0];
        
        User *landlord = [[User alloc] init];
        landlord.userID = [userInfo[@"user_id"] intValue];
        landlord.userPhone = userInfo[@"user_phone"];
        landlord.userName = userInfo[@"user_name"];
        landlord.userHead = userInfo[@"user_head"];
        landlord.userRegisterTime = [userInfo[@"user_register_time"] doubleValue];
        landlord.userMail = userInfo[@"user_mail"];
        
        //加载界面
        [self loadPerson:landlord];
        //关闭缓冲动画
        [HUD removeFromSuperViewOnHide];
        HUD = nil;
    }else{
        //没有得到信息
        [HUD removeFromSuperViewOnHide];
        HUD = nil;
        
        //提示
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        HUD.mode = MBProgressHUDModeText;
        HUD.labelText = @"没有获取得房东的信息-_-!#";
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperViewOnHide];
            HUD = nil;
        }];
    }
}

#pragma mark 请求失败的方法：
-(void)requestFailed:(ASIHTTPRequest *)request{
    [HUD removeFromSuperViewOnHide];
    HUD = nil;
    
    //提示
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.mode = MBProgressHUDModeText;
    HUD.labelText = @"获取房东信息失败-_-!#";
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [HUD removeFromSuperViewOnHide];
        HUD = nil;
    }];
}

#pragma mark - 添加图片功能所有函数
#pragma mark - actionsheet代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"照相");
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            //设置代理
            imagePicker.delegate = self;
            //判断是否有后置摄像头
            if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
                NSLog(@"没有摄像头");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//照相机
            //调用摄像头开始拍照
            [self presentViewController:imagePicker animated:YES completion:^{
            }];
            break;
        }
        case 1:
        {
            NSLog(@"选照片");
            //创建照片选取器
            ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
            picker.maximumNumberOfSelection = 1;
            picker.assetsFilter = [ALAssetsFilter allPhotos];
            picker.showEmptyGroups=NO;
            picker.delegate=self;
            picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
                if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                    NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                    return duration >= 5;
                } else {
                    return YES;
                }
            }];
            
            [self presentViewController:picker animated:YES completion:NULL];
            
        }
            
            break;
            
        case 2:
            NSLog(@"cancel");
            return;
            break;
    }
}



#pragma mark - UIImagePickerController代理方法，拍照结束后全调用这个方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取拍到的照片
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //将image转化成NSData
    imageData = UIImageJPEGRepresentation(image, kCompressionRatio);
    //图片加入数组后，将拍照这个界面关闭
    loadHeadView.headImageView.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
   [self submitHouseImages:imageData userID:del.currentUser.userID];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    
    //选取照片数组的第一张，把它添加到头像视图上面
    ALAsset *asset = assets[0];
    UIImage *image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
    imageData = UIImageJPEGRepresentation(image, kCompressionRatio);
    loadHeadView.headImageView.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self submitHouseImages:imageData userID:del.currentUser.userID];
   
    
}

#pragma mark 上传头像图片
-(void)submitHouseImages:(NSData *)imagedata userID:(int)userID
{
    
    //上传图片
    NSString *urlstr = [NSString stringWithFormat:@"%@Upload/upload",kHTTPHome];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlstr]];
    
    [request setValidatesSecureCertificate:NO];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"Content-Type" value:@"binary/octet-stream"];
    [request setRequestMethod:@"POST"];
    
    //传递userID和图片类型信息
    [request setPostValue:@"userHead" forKey:@"subfileName"];
    [request setPostValue:[NSString stringWithFormat:@"%d",userID] forKey:@"subID"];
    
    [request addData:imagedata withFileName:@"header.png" andContentType:@"image/png" forKey:@"file"];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    NSString *messagge = [dic objectForKey:@"message"];
    NSLog(@"ghjnjj   %@",messagge);
    NSLog(@"%d",status);
    if (status) {
        [self loadheadname:del.currentUser.userID];
    }else{
        NSLog(@"head-------fail");
    }

    
}
#pragma mark - 通过userid重新获得usehead
-(void)loadheadname:(int )userid
{
    
    NSString *urlstr = [NSString stringWithFormat:@"%@User/information",kHTTPHome];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlstr]];
    [request setRequestMethod:@"POST"];
    [request setPostValue:[NSString stringWithFormat:@"%d",userid] forKey:@"userID"];
    [request startSynchronous];
    NSData *data = [request responseData];
    NSDictionary *dic = [jd objectWithData:data];
    NSArray *userarray= [dic objectForKey:@"user"];
    NSDictionary *userdic = [userarray objectAtIndex:0];
    NSString *head = [userdic objectForKey:@"user_head"];
    del.currentUser.userHead = head ;
}


@end
